#include "Scene.hpp"
#include "3D/TerrainFactory.hpp"

Scene::Scene():
    _name(""),
    _path(""),
    _terrain(NULL)
{

}

Scene::Scene(std::string const& name, std::string const& path, Terrain* terrain):
    _name(name),
    _path(path),
    _terrain(terrain)
{
}

Scene::~Scene()
{
    delete _terrain;

    std::list<DrawableObject*>::iterator    itBegin = _objects.begin();
    std::list<DrawableObject*>::iterator    itEnd = _objects.end();

    while (itBegin != itEnd)
    {
        delete *itBegin;
        ++itBegin;
    }
}

void    Scene::draw(Shader* shader)
{
    if (_terrain != NULL)
    {
        _terrain->getDrawable()->setShader(shader);
        _terrain->draw();
    }

    std::list<DrawableObject*>::iterator    itBegin = _objects.begin();
    std::list<DrawableObject*>::iterator    itEnd = _objects.end();

    while (itBegin != itEnd)
    {
        (*itBegin)->setShader(shader);
        (*itBegin)->draw();
        ++itBegin;
    }
}

void    Scene::update()
{
    if (_terrain != NULL)
        _terrain->update();
}

DrawableObject*     Scene::findObject(const unsigned char r, const unsigned char g, const unsigned char b)
{
    std::list<DrawableObject*>::iterator    itBegin = _objects.begin();
    std::list<DrawableObject*>::iterator    itEnd = _objects.end();
    int                                     index = 0;

    while (itBegin != itEnd)
    {
        if ((*itBegin)->findVertex(r, g, b, index) != NULL)
        {
            return *itBegin;
        }
        ++itBegin;
    }
    return NULL;
}

const std::string &Scene::getName() const
{
    return _name;
}

void            Scene::setName(std::string const& name)
{
    _name = name;
}

const std::string &Scene::getPath() const
{
    return _path;
}

void            Scene::setPath(std::string const& path)
{
    _path = path;
}

Terrain*        Scene::getTerrain()
{
    return _terrain;
}

void            Scene::setTerrain(Terrain* terrain)
{
    _terrain = terrain;
    if (terrain != NULL)
        _terrain->getDrawable()->init();
}

void            Scene::addObject(DrawableObject *object)
{
    _objects.push_back(object);
}

std::list<DrawableObject*>& Scene::getObjects()
{
    return _objects;
}

